package com.nnnu.orange.controller.admin;


import com.nnnu.orange.constant.JwtClaimsConstant;
import com.nnnu.orange.constant.MessageConstants;
import com.nnnu.orange.constant.StatusCodeConstants;
import com.nnnu.orange.pojo.dto.LoginDto;
import com.nnnu.orange.pojo.entity.Admin;
import com.nnnu.orange.properties.JwtProperties;
import com.nnnu.orange.result.Result;
import com.nnnu.orange.service.IAdminService;
import com.nnnu.orange.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zk
 * @since 2024-11-07
 */
@RestController
@RequestMapping("/admin")
@RequiredArgsConstructor
@Slf4j
public class AdminController {

    private final IAdminService iAdminService;
    private final JwtProperties jwtProperties;


    /**
     * 管理端登录
     *
     * @param loginDto dto
     * @return token
     */
    @PostMapping("/login")
    public Result<String> login(@RequestBody LoginDto loginDto) {
        log.info("管理员登录:{}", loginDto);
        Admin admin = iAdminService.login(loginDto);
        //生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, admin.getAdminId());
        String token = JwtUtil.createJwt(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), claims);
        return Result.success(token, MessageConstants.LOGIN_SUCCESS);

    }


    /**
     * 管理端退出
     *
     * @return 提示
     */
    @PostMapping("/logout")
    public Result<String> logout(@RequestHeader("Authorization") String token) {
        if (StringUtils.isBlank(token)) {
            return Result.error(StatusCodeConstants.UNAUTHORIZED, "資源訪問失敗");
        }

        // 解析 token 获取管理员 ID
        long adminId = JwtUtil.parseTokenId(jwtProperties.getAdminSecretKey(), token);

        if (adminId == 0) {
            return Result.error(StatusCodeConstants.UNAUTHORIZED, "資源訪問失敗");
        }
        // 返回退出登录成功消息
        return Result.success("退出成功");
    }

}
